package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.packageSelling;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.PackageSellingDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.ExportPackageSellingExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.CPdtsAuthServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.impl.CWeightSheetsServiceImpl;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetAllPackageSellingVo;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.excel.strategy.ExcelWidthStyleStrategy;
import com.xiaoxu.intranetweb.util.excel.strategy.MergeCellStrategyHandler;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.rocketmq.shaded.com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Future;

@Component
public class PackageSellingBu {
    @Autowired
    private ITPackageSellingService packageSellingService;
    @Autowired
    private ICCompanysService companysService;
    @Autowired
    private ICProductsInfoService productsInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private UserInfoDao  userInfoDao;
    @Autowired
    private PackageSellingDic packageSellingDic;
    @Autowired
    private ICCompanysService  cCompanysService;
    @Autowired
    private ICProductsInfoService  cProductsInfoService;
    @Autowired
    private ISysUserService  iSysUserService;
    @Autowired
    private ITSpecialPriceService  tSpecialPriceService;
    @Autowired
    private ITSpecialPriceTypeService specialPriceTypeService;
    @Autowired
    private CWeightSheetsServiceImpl weightSheetsService;
    @Autowired
    private CPdtsAuthServiceImpl pdtsAuthService;
    @Autowired
    private SysLogBu sysLogBu;
    public SzResult getAllPackageSelling(Integer page,Integer pageSize,String startTime,String endTime,String pdtId,String coId,String plantId) {
        Page<TPackageSelling> page1 = new Page<>(page, pageSize);
        QueryWrapper<TPackageSelling> wrapper = new QueryWrapper<>();
        if (plantId != null) {
            wrapper.eq("DATA_FROM", plantId);
        }
        if (coId != null && !coId.equals("")) {
            wrapper.eq("CO_ID", coId);
        }
        if (pdtId != null && !pdtId.equals("")) {
            wrapper.eq("PDT_ID", pdtId);
        }
        wrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" +endTime+ "'" + " ) " + " or " +
                " ( " + " END_TIME " + " >= " + "'" +startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime+ "'" + " ) " + " or " +
                " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" +endTime + "'" + " ) " + " or " +
                " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");
        wrapper.orderByDesc("CREATE_TIME");
        IPage<TPackageSelling> trucksVos = packageSellingService.page(page1, wrapper);
        List<TPackageSelling> records = trucksVos.getRecords();
        List<GetAllPackageSellingVo> list = new ArrayList<>();
        long total = trucksVos.getTotal();
        for (int i = 0; i <records.size() ; i++) {
            GetAllPackageSellingVo vo = new GetAllPackageSellingVo();
            vo.setId( trucksVos.getRecords().get(i).getId());
            vo.setCoId( trucksVos.getRecords().get(i).getCoId());
            vo.setPdtId( trucksVos.getRecords().get(i).getPdtId());
            vo.setStartTime( trucksVos.getRecords().get(i).getStartTime());
            vo.setEndTime( trucksVos.getRecords().get(i).getEndTime());
            vo.setNum( trucksVos.getRecords().get(i).getNum());
            vo.setPrice( trucksVos.getRecords().get(i).getPrice());
            vo.setDataFrom( trucksVos.getRecords().get(i).getDataFrom());
            vo.setCreateTime( trucksVos.getRecords().get(i).getCreateTime());
            vo.setCreaterId( trucksVos.getRecords().get(i).getCreaterId());
            vo.setPackageDesc( trucksVos.getRecords().get(i).getPackageDesc());
            vo.setUpdateTime( trucksVos.getRecords().get(i).getUpdateTime());
            vo.setUpdaterId( trucksVos.getRecords().get(i).getUpdaterId());
            if (trucksVos.getRecords().get(i).getUpdaterId() !=null) {
                QueryWrapper<SysUser> wrapper4 = new QueryWrapper<>();
                wrapper4.eq("ID", vo.getUpdaterId());
                SysUser sysUser1 = userService.getOne(wrapper4);
                vo.setUpdaterName(sysUser1.getTrueName());
            }
            QueryWrapper<SysUser> wrapper0 = new QueryWrapper<>();
            wrapper0.eq("ID", vo.getCreaterId());
            SysUser sysUser = userService.getOne(wrapper0);
            vo.setCreaterName(sysUser.getTrueName());
            if (trucksVos.getRecords().get(i).getUpdaterId() != null && !trucksVos.getRecords().get(i).getUpdaterId().equals("")) {
                vo.setUpdaterId(trucksVos.getRecords().get(i).getUpdaterId());
                QueryWrapper<SysUser> wrapper3 = new QueryWrapper<>();
                wrapper3.eq("ID", vo.getCreaterId());
                SysUser sysUser1 = userService.getOne(wrapper3);
                vo.setUpdaterName(sysUser1.getTrueName());
            }
            vo.setSellType( trucksVos.getRecords().get(i).getSellType());
            QueryWrapper<CCompanys> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("ID", vo.getCoId());
            CCompanys cCompanys = companysService.getOne(wrapper1);
            vo.setCoName(cCompanys.getCpyCo()+"."+cCompanys.getCpyChico());
            QueryWrapper<CProductsInfo> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("ID", vo.getPdtId());
            CProductsInfo cProductsInfo = productsInfoService.getOne(wrapper2);
            vo.setPdtName(cProductsInfo.getPdtinfPdt());
            list.add(vo);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", list);
        return SzResult.success(map);
    }

//      新增打包销售
    public SzResult addPackageSelling(List coIds, List pdtIds, String startTime, String endTime, BigDecimal price,BigDecimal num,Integer sellType,String desc,String dataFrom,String token) throws Exception {
        if (sellType==2){
            return  SzResult.error("新增失败,暂不支持数量类型的打包销售");
        }
        for (Object coId : coIds) {
            for (Object pdtId : pdtIds) {
                //        查一下这个区间里是否已经存在数据了
                QueryWrapper<TPackageSelling> wrapper = new QueryWrapper<>();
                wrapper.eq("DATA_FROM", dataFrom);
                wrapper.eq(coId !=null,"CO_ID", coId);
                wrapper.eq(pdtId !=null,"PDT_ID", pdtId);
                wrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" +endTime+ "'" + " ) " + " or " +
                        " ( " + " END_TIME " + " >= " + "'" +startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime+ "'" + " ) " + " or " +
                        " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" +endTime + "'" + " ) " + " or " +
                        " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");

                List<TPackageSelling> list = packageSellingService.list(wrapper);
                if (list.size()>0){
                    return  SzResult.error("该时间区间里，该单位已有该品种的打包销售数据了");
                }
                TPackageSelling packageSelling = new TPackageSelling();
//        创建uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                packageSelling.setId(uuid);
                packageSelling.setCoId((String) coId);
                packageSelling.setPdtId((String) pdtId);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                packageSelling.setStartTime(LocalDateTime.parse(startTime.replace("T", " "),formatter));
                packageSelling.setEndTime(LocalDateTime.parse(endTime.replace("T", " "),formatter));
                packageSelling.setPrice(price);
                packageSelling.setNum(num);
                packageSelling.setSellType(sellType);
                packageSelling.setPackageDesc(desc);
                packageSelling.setDataFrom(dataFrom);
                SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
                packageSelling.setCreaterId(sysUser.getId());
                packageSelling.setCreateTime(LocalDateTime.now().format(formatter));
                this.insertSpecialPrice(packageSelling,dataFrom);
                packageSellingService.save(packageSelling);
            }
        }
        return SzResult.success("新增成功");
    }
//修改打包销售数据
    public SzResult updatePackageSelling(String id,String coId, String pdtId, String startTime, String endTime, BigDecimal price,BigDecimal num,Integer sellType,String desc,String dataFrom,String token) throws Exception {
//        查一下这个区间里是否已经存在数据了
        QueryWrapper<TPackageSelling> wrapper = new QueryWrapper<>();
        wrapper.ne("ID", id);
        wrapper.eq(coId !=null,"CO_ID", coId);
        wrapper.eq(pdtId !=null,"PDT_ID", pdtId);
        wrapper.eq("DATA_FROM", dataFrom);
        wrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" +endTime+ "'" + " ) " + " or " +
                " ( " + " END_TIME " + " >= " + "'" +startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime+ "'" + " ) " + " or " +
                " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" +endTime + "'" + " ) " + " or " +
                " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");
        List<TPackageSelling> list = packageSellingService.list(wrapper);
        if (list.size()>0){
            return  SzResult.Error("修改的时间后的区间，已存在其他打包数据");
        }
        QueryWrapper<TPackageSelling> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("ID", id);
        TPackageSelling packageSelling = packageSellingService.getOne(wrapper1);
        packageSelling.setCoId(coId);
        packageSelling.setPdtId(pdtId);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        packageSelling.setStartTime(LocalDateTime.parse(startTime.replace("T", " "),formatter));
        packageSelling.setEndTime(LocalDateTime.parse(endTime.replace("T", " "),formatter));
        packageSelling.setPrice(price);
        packageSelling.setNum(num);
        packageSelling.setSellType(sellType);
        packageSelling.setPackageDesc(desc);
        packageSelling.setDataFrom(dataFrom);
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        packageSelling.setUpdaterId(sysUser.getId());
        packageSelling.setUpdateTime(LocalDateTime.parse(LocalDateTime.now().format(formatter),formatter));
        this.updatePackageSelling(packageSelling,dataFrom);
        return SzResult.success(packageSellingService.updateById(packageSelling));
    }
//       删除打包销售数据
    public SzResult deletePackageSelling(String id, String dataFrom, String token) throws Exception {
        SysUser sysUser = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<TPackageSelling> wrapper = new QueryWrapper<>();
        wrapper.eq("ID", id);
        wrapper.eq("DATA_FROM", dataFrom);
        TPackageSelling packageSelling = packageSellingService.getOne(wrapper);
        if (packageSelling.getStartTime().isBefore(LocalDateTime.now())){
            return SzResult.error("无法删除，已经过了执行开始时间了！");
        }
        packageSellingService.removeById(id);
            this.deleteSpecialPrice(id, dataFrom);
            CCompanys cCompanys = cCompanysService.getById(packageSelling.getCoId());
            CProductsInfo cProductsInfo = cProductsInfoService.getById(packageSelling.getPdtId());
        sysLogBu.logRecord("打包销售",sysUser.getTrueName(),"删除了单位【"+cCompanys.getCpyCo()+"."+cCompanys.getCpyChico()+"】"+"、"+"品种【"+cProductsInfo.getPdtinfPdt()+"】、"+"价格【"+packageSelling.getPrice()+"】、执行时间为【"+packageSelling.getStartTime()+"~"+packageSelling.getEndTime()+"】的数据",dataFrom);
        return SzResult.Success();
    }
    //将数据写入t_special_price
    public void insertSpecialPrice(TPackageSelling tPackageSelling, String plantId){
        TSpecialPrice tSpecialPrice = new TSpecialPrice();
        tSpecialPrice.setPriceTypeId("0705df3110c911ef823f00ff8a757bed");
        TSpecialPriceType tSpecialPriceType = specialPriceTypeService.getById("0705df3110c911ef823f00ff8a757bed");
        tSpecialPrice.setPriceType(tSpecialPriceType.getPriceTypeName());
        tSpecialPrice.setCoId(tPackageSelling.getCoId());
        tSpecialPrice.setPdtId(tPackageSelling.getPdtId());
        tSpecialPrice.setExecuteType(tPackageSelling.getSellType());
        tSpecialPrice.setPrice(tPackageSelling.getPrice());
        tSpecialPrice.setNum(tPackageSelling.getNum());
        tSpecialPrice.setResidueNum(tPackageSelling.getNum());
        tSpecialPrice.setStartTime(tPackageSelling.getStartTime());
        tSpecialPrice.setEndTime(tPackageSelling.getEndTime());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        tSpecialPrice.setCreateTime(LocalDateTime.parse(tPackageSelling.getCreateTime().replace("T", " "),formatter));
        tSpecialPrice.setCreaterId(tPackageSelling.getCreaterId());
        tSpecialPrice.setConnId(tPackageSelling.getId());
        tSpecialPrice.setDataFrom(plantId);
        tSpecialPriceService.save(tSpecialPrice);
    }
//    修改数据写入t_special_price
    public void updatePackageSelling(TPackageSelling tPackageSelling, String plantId){
        QueryWrapper<TSpecialPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("CONN_ID", tPackageSelling.getId());
        TSpecialPrice tSpecialPrice = tSpecialPriceService.getOne(wrapper);
        // 计算已经消耗的数量
        BigDecimal consumedNum = tSpecialPrice.getNum().subtract(tSpecialPrice.getResidueNum());
        tSpecialPrice.setPriceTypeId("0705df3110c911ef823f00ff8a757bed");
        TSpecialPriceType tSpecialPriceType = specialPriceTypeService.getById("0705df3110c911ef823f00ff8a757bed");
        tSpecialPrice.setPriceType(tSpecialPriceType.getPriceTypeName());
        tSpecialPrice.setCoId(tPackageSelling.getCoId());
        tSpecialPrice.setPdtId(tPackageSelling.getPdtId());
        tSpecialPrice.setExecuteType(tPackageSelling.getSellType());
        tSpecialPrice.setPrice(tPackageSelling.getPrice());
        tSpecialPrice.setNum(tPackageSelling.getNum());
        //        修改时考虑剩余量问题

        // 根据新的总量和已经消耗的数量来更新剩余量
        tSpecialPrice.setResidueNum(tPackageSelling.getNum().subtract(consumedNum));
        tSpecialPrice.setStartTime(tPackageSelling.getStartTime());
        tSpecialPrice.setEndTime(tPackageSelling.getEndTime());
        tSpecialPrice.setUpdateTime(tPackageSelling.getUpdateTime());
        tSpecialPrice.setUpdatorId(tPackageSelling.getUpdaterId());
        tSpecialPrice.setConnId(tPackageSelling.getId());
        tSpecialPrice.setDataFrom(plantId);
        tSpecialPriceService.updateById(tSpecialPrice);
    }
//    删除t_special_price数据
    public void deleteSpecialPrice(String id, String dataFrom){
        QueryWrapper<TSpecialPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("CONN_ID", id);
        wrapper.eq("DATA_FROM", dataFrom);
        tSpecialPriceService.remove(wrapper);
    }

//    导出打包销售数据
    @Async
    public Future<List<ExportPackageSellingExcelEn>> exportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader,
                                                                 String mode, Boolean original, Map<String, String> pager, String sheetName, Map<String, String> form, String plantId) throws Exception {
        List<Map<String, Object>> newIds = new ArrayList<>();
        List<ExportPackageSellingExcelEn> exportPackageSellings = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        ExportPackageSellingExcelEn exportPackageSelling = ExportPackageSellingExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("coName")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCoName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPdtName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("price")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("sellType")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setSellType(packageSellingDic.sellTypeDic(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("num")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("startTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setStartTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("endTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("creater")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCreater(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCreateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setUpdateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updater")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setUpdater(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("packageDesc")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPackageDesc(entry.getValue().toString());
                                }
                            }
                        }
                        exportPackageSellings.add(exportPackageSelling);
                    }
                    break;
                case "all":
                    String startTime = form.get("startTime");
                    String endTime = form.get("endTime");
                    String pdtId = form.get("pdtId");
                    String coId = form.get("coId");
                    List<ExportPackageSellingExcelEn> exportPackageSelling1 = new ArrayList<>();
                    QueryWrapper<TPackageSelling> wrapper = new QueryWrapper<>();
                    wrapper.eq("DATA_FROM", plantId);
                    if (pdtId != null) {
                        wrapper.eq(!pdtId.equals(""),"PDT_ID",pdtId);
                    }
                    if (coId !=null) {
                        wrapper.eq(!coId.equals(""), "CO_ID", coId);
                    }
                    wrapper.apply("(" + "(" + "START_TIME" + " >= " + "'" + startTime + "'" + " AND " + " START_TIME " + " <= " + "'" +endTime+ "'" + " ) " + " or " +
                            " ( " + " END_TIME " + " >= " + "'" +startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime+ "'" + " ) " + " or " +
                            " ( " + "START_TIME" + " <= " + "'" + startTime + "'" + " AND " + " END_TIME " + " >= " + "'" +endTime + "'" + " ) " + " or " +
                            " ( " + " START_TIME " + " >=" + "'" + startTime + "'" + " AND " + " END_TIME " + " <= " + "'" + endTime + "'" + " ) " + ")");
                    List<TPackageSelling> list = packageSellingService.list(wrapper);
                    for (TPackageSelling tPackageSelling : list) {
                         CCompanys CCompany = cCompanysService.getById(tPackageSelling.getCoId());
                        ExportPackageSellingExcelEn exportPackageSelling2 = ExportPackageSellingExcelEn.builder()
                                .coName(Optional.of(CCompany.getCpyCo()+"."+CCompany.getCpyChico()).map(Object::toString).orElse(""))
                                .pdtName(Optional.ofNullable(cProductsInfoService.getById(tPackageSelling.getPdtId()).getPdtinfPdt()).map(Object::toString).orElse(""))
                                .price(tPackageSelling.getPrice())
                                .sellType(Optional.ofNullable(packageSellingDic.sellTypeDic(tPackageSelling.getSellType().toString())).map(Object::toString).orElse(""))
                                .num(Optional.ofNullable(tPackageSelling.getNum()).map(Object::toString).orElse(""))
                                .startTime(Optional.ofNullable(tPackageSelling.getStartTime()).map(Object::toString).orElse(""))
                                .endTime(Optional.ofNullable(tPackageSelling.getEndTime()).map(Object::toString).orElse(""))
                                .createTime(Optional.ofNullable(tPackageSelling.getCreateTime()).map(Object::toString).orElse(""))
                                .creater(Optional.ofNullable(iSysUserService.getById(tPackageSelling.getCreaterId()).getTrueName()).map(Object::toString).orElse(""))
                                .updateTime(Optional.ofNullable(tPackageSelling.getUpdateTime()).map(Object::toString).orElse(""))
                                .updater(Optional.ofNullable(iSysUserService.getById(tPackageSelling.getUpdaterId()).getTrueName()).map(Object::toString).orElse(""))
                                .packageDesc(Optional.ofNullable(tPackageSelling.getPackageDesc()).map(Object::toString).orElse(""))
                                .build();
                        exportPackageSelling1.add(exportPackageSelling2);
                    }
                    exportPackageSellings = exportPackageSelling1;
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
                    for (Map<String, Object> newId : newIds) {
                        ExportPackageSellingExcelEn exportPackageSelling = ExportPackageSellingExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
                            if (entry.getKey().equals("coName")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCoName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPdtName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("price")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPrice(new BigDecimal(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("sellType")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setSellType(packageSellingDic.sellTypeDic(entry.getValue().toString()));
                                }
                            }
                            if (entry.getKey().equals("num")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setNum(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("startTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setStartTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("endTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setEndTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("creater")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCreater(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setCreateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updateTime")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setUpdateTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("updater")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setUpdater(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("packageDesc")) {
                                if (entry.getValue() != "" && entry.getValue() != null) {
                                    exportPackageSelling.setPackageDesc(entry.getValue().toString());
                                }
                            }
                        }
                        exportPackageSellings.add(exportPackageSelling);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(exportPackageSellings);
    }
    public void salesStatisticExcel(List<String>  clientIds, List<String> productIds, String startTime , String endTime, HttpServletResponse response) throws Exception {
        //填写标题
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日");
        String start = outputFormat.format(inputFormat.parse(startTime));
        String end = outputFormat.format(inputFormat.parse(endTime));
        String title = start + "至" + end + "打包销售统计表";
        List<List<String>> headList = new ArrayList<>();
        headList.add(Lists.newArrayList(title,"序号"));
        headList.add(Lists.newArrayList(title,"类型"));
        headList.add(Lists.newArrayList(title,"客户名称"));
        headList.add(Lists.newArrayList(title,"品种"));
        headList.add(Lists.newArrayList(title,"报价（元/吨）"));
        headList.add(Lists.newArrayList(title,"总报量（吨）"));
        headList.add(Lists.newArrayList(title,"总拉运量（吨）"));
        //增加选定日期标题
        LocalDate startDate = LocalDate.parse(startTime,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = LocalDate.parse(endTime,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<String> dateList = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            headList.add(Lists.newArrayList(title, startDate.format(DateTimeFormatter.ofPattern("MM月dd日"))));
            dateList.add(startDate.format((DateTimeFormatter.ofPattern("yyyy-MM-dd"))));
            startDate = startDate.plusDays(1);
        }
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景色
//            headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 12);
        headWriteCellStyle.setWriteFont(headWriteFont);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景绿色
//        contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 11);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置 垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.DASHED);
        contentWriteCellStyle.setBorderTop(BorderStyle.DASHED);
        contentWriteCellStyle.setBorderRight(BorderStyle.DASHED);
        contentWriteCellStyle.setBorderBottom(BorderStyle.DASHED);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(title, "UTF-8") + ".xlsx");
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        Set<Integer> columnIndices = Collections.unmodifiableSet(
                new LinkedHashSet<>(Arrays.asList(0,1,2))
        );
        WriteSheet writeSheet = EasyExcel.writerSheet(title)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new SimpleRowHeightStyleStrategy((short) 30, (short) 24))//设置行高
                .registerWriteHandler(new ExcelWidthStyleStrategy(0))//自动列宽
                .registerWriteHandler(new MergeCellStrategyHandler(true,true, 1, columnIndices))
                .build();

        for (int i = 0; i < clientIds.size(); i++) {
            CCompanys company = cCompanysService.getById(clientIds.get(i));
            List<List<Object>> data = new ArrayList<>();
            WriteTable writeTable = EasyExcel.writerTable(i).head(headList).needHead(Boolean.TRUE).build();
            //序号
            for (String productId : productIds) {
                CProductsInfo productsInfo = productsInfoService.getById(productId);
                QueryWrapper<TPackageSelling> packageSellingQueryWrapper = new QueryWrapper<>();
                packageSellingQueryWrapper.eq("CO_ID",clientIds.get(i));
                packageSellingQueryWrapper.eq("PDT_ID",productId);
                packageSellingQueryWrapper.ge("START_TIME",startTime + " 00:00:00");
                packageSellingQueryWrapper.le("END_TIME",endDate + " 23:59:59");
                TPackageSelling packageSelling = packageSellingService.getOne(packageSellingQueryWrapper);
                if (packageSelling != null) {
                    List<Object> list = new ArrayList<>();
                    list.add(i);
                    list.add(" ");
                    list.add(company.getCpyShrtname());
                    list.add(productsInfo.getPdtinfPdt());
                    QueryWrapper<CPdtsAuth> pdtsAuthQueryWrapper = new QueryWrapper<CPdtsAuth>();
                    pdtsAuthQueryWrapper.eq("PDTSAUTH_CO",company.getCpyCo());
                    pdtsAuthQueryWrapper.eq("PDTSAUTH_CHICO",company.getCpyChico());
                    pdtsAuthQueryWrapper.eq("PDTSAUTH_PDT",productsInfo.getPdtinfPdt());
                    CPdtsAuth pdtsAuth = pdtsAuthService.getOne(pdtsAuthQueryWrapper);
                    list.add(packageSelling.getPrice().add(pdtsAuth.getPdtsauthPrice()));
                    list.add("");
                    List<BigDecimal> numList = new ArrayList<>();
                    for (String date : dateList) {
                        QueryWrapper<CWeightSheets> weightSheetsQueryWrapper = new QueryWrapper<>();
                        weightSheetsQueryWrapper.eq("WEISHT_PRODUCT",productsInfo.getPdtinfPdt());
                        weightSheetsQueryWrapper.eq("WEISHT_CO",company.getCpyCo());
                        weightSheetsQueryWrapper.eq("WEISHT_CHI_CO",company.getCpyChico());
                        weightSheetsQueryWrapper.eq("WEISHT_PRICE_TYPE","打包销售");
                        weightSheetsQueryWrapper.ge("WEISHT_FULL_TM",date+" 00:00:00");
                        weightSheetsQueryWrapper.le("WEISHT_FULL_TM",date+" 23:59:59");
                        weightSheetsQueryWrapper.le("WEISHT_BACKED",1);
                        weightSheetsQueryWrapper.le("WEISHT_DEDUCTION",1);
                        weightSheetsQueryWrapper.le("WEISHT_DELETED",0);
                        weightSheetsQueryWrapper.select("WEISHT_NET_WGHT");
                        BigDecimal num = weightSheetsService.list(weightSheetsQueryWrapper).stream()
                                .map(item -> item.getWeishtNetWght())
                                .reduce(BigDecimal.valueOf(0), BigDecimal::add);
                        numList.add(num);
                    }
                    list.add(numList.stream().reduce(BigDecimal.valueOf(0), BigDecimal::add));
                    list.addAll(numList);
                    data.add(list);
                }
            }
            excelWriter.write(data, writeSheet, writeTable);
        }
        excelWriter.finish();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}
